import { isNull, deepEqual, deepClone } from "@/utils/service";
import { TABLE_ENUM } from "@/components/table/enum";

class TbColumn {

  constructor(label, prop, {
    width,
    minWidth,
    fixed,
    sortable = false,
    formatter,
    headerAlign,
    align = "center",
    showOverflowTooltip = true,
    /*是否允许拖动改变列顺序 fixed = true 时也不能拖动*/
    dragAble = true,
    /*是否启用 (用于用户控制某列是否可见)*/
    enabled = true,
    /*是否显示 (用于权限控制 比如 a 列对某用户不可见时)*/
    show = true,
    /* 是否可以过滤*/
    filterAble = false,
    /* 过滤模式 */
    filterMode,
    /* 过滤值*/
    filterValue
  }) {
    if (isNull(label) || isNull(prop)) {
      throw new Error("Both 'label' and 'prop' are required.");
    }
    this.label = label;
    this.prop = prop;
    this.width = width;
    this.minWidth = minWidth;
    this.fixed = fixed;
    this.sortable = sortable;
    this.formatter = formatter;
    this.headerAlign = headerAlign;
    this.align = align;
    this.showOverflowTooltip = showOverflowTooltip;
    this.dragAble = dragAble;
    this.enabled = enabled;
    this.show = show;
    this.filterAble = filterAble;
    this.filterMode = filterMode;
    this.filterValue = filterValue;
    this.filterModeValidity();
  }

  static builder(label, prop) {
    return new this(label, prop, {});
  }

  /**
   * 初始化过滤值
   * */
  initFilterValue() {
    this.filterValue = deepClone(TABLE_ENUM.FilterDefValueEnum[this.filterMode]);
  }

  /** 过滤是否生效*/
  isFilterActive() {
    return this.enabled && this.show && this.filterAble;
  }

  /** 过滤值是否满足条件生效 */
  filterValueActive() {
    return this.isFilterActive() && !isNull(this.filterValue) && !deepEqual(TABLE_ENUM.FilterDefValueEnum[this.filterMode], this.filterValue);
  }

  /** 校验过滤模式合法性*/
  filterModeValidity() {
    // 列生效 且 开启过滤时校验过滤模式有效性
    if (!this.isFilterActive()) {
      return;
    }
    if (Object.values(TABLE_ENUM.FilterModeEnum).includes(this.filterMode)) {
      return;
    }
    throw new Error(`非法的过滤模式 label : ${this.label} mode: ${this.filterMode}`);
  }

  getRef() {
    return `col_filter_${this.prop}`;
  }

  /** 构建请求参数 */
  static buildReqParams(columns) {
    columns = columns
      .filter(col => col.filterValueActive());
    if (columns.length === 0) {
      return undefined;
    }
    return columns.map(col => {
      return {
        prop: col.prop,
        mode: col.filterMode,
        value: JSON.stringify(col.filterValue)
      };
    });
  }

  static build(column) {
    let v = deepClone(column);
    return new TbColumn(v.label, v.prop, v);
  }

  static buildArray(columns) {
    return columns.map(column => TbColumn.build(column));
  }
}

export default TbColumn;

